//
//  AppDelegate.m
//  danpin
//
//  Created by chuangjia on 17/6/15.
//  Copyright (c) 2015 chuangjia. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseModel.h"
#import "BaiChuanShare.h"
#import "RootViewController.h"
#import "ZPlatformShare.h"
#import "SDImageCache.h"
#import "UMengShare.h"
#import "AlipayHeader.h"
#import "orderconfig.h"
#import "IntroView.h"
#import "ZApi.h"
#import "UIImage+GIF.h"

#import "StorageInfo.h"
#import "ZSpotLightHelper.h"
//todo : 从后台激活，冷却超过15分钟就重新刷新首页
void UncaughtExceptionHandler(NSException *exception) {
    /**
     *  获取异常崩溃信息
     */
    NSArray *callStack = [exception callStackSymbols];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    NSString *content = [NSString stringWithFormat:@"========异常错误报告========\nname:%@\nreason:\n%@\ncallStackSymbols:\n%@",name,reason,[callStack componentsJoinedByString:@"\n"]];
    
    /**
     *  把异常崩溃信息发送至开发者邮件
     */
    NSMutableString *mailUrl = [NSMutableString string];
    [mailUrl appendString:@"mailto:liuchengbin@danpin.com"];
    [mailUrl appendString:@"?subject=程序异常崩溃，请配合发送异常报告，谢谢合作！"];
    [mailUrl appendFormat:@"&body=%@", content];
    // 打开地址
    NSString *mailPath = [mailUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mailPath]];
}

@interface AppDelegate ()<UIAlertViewDelegate,IntroViewDelegate>
{
    
}
@property(nonatomic,strong)NSString *urlstr;
@property(nonatomic,strong)RootViewController *rootView;
@property(nonatomic,strong)IntroView *introView;
@end

@implementation AppDelegate

@synthesize orderDelegate=_orderDelegate;
////////////////////////////
- (UIImage*) imgLoading
{
    if(_imgLoading == nil)
    {
        _imgLoading = [UIImage sd_animatedGIFNamed:@"loading"];
    }
    return _imgLoading;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [self imgLoading];//提前把GIF加载好，避免用户下拉刷新的时候界面卡住

#ifdef DEBUG
    NSSetUncaughtExceptionHandler(&UncaughtExceptionHandler);
#endif
    
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    
    //
    // IOS8 新系统需要使用新的代码咯
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
                                                                             settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                                                             categories:nil]];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        //这里还是原来的代码
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }
    
    //初始化分享平台信息
    [ZPlatformShare initPlatformData];
    //百川数据包 sdk初始化
    [[BaiChuanShare sharedInstance] initSDK:NO];
    [[BaiChuanShare sharedInstance] setSessionStateChangedHandler];
    //umeng
    [[UMengShare sharedInstance] initSDK:NO];
    //
    [self initStat];
    //
    _rootView = [[RootViewController alloc] init];
    _nav =[[UINavigationController alloc] initWithRootViewController:_rootView];
    [_nav setEnableBackGesture:YES];
    _nav.navigationBarHidden =YES;
    self.window.rootViewController = _nav;
    [self.window makeKeyAndVisible];
    [self initIntroView];
   
    // 处理推送
    if (launchOptions != nil) {
        NSDictionary *dictionary = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (dictionary != nil) {
            // 这个字典就是推送消息的userInfo
            id aps = [dictionary objectForKey:@"aps"];
            if (aps && [aps isKindOfClass:[NSDictionary class]]){
                NSString *posturl =[aps stringForKey:@"post_url" withDefaultValue:@""];
                if (posturl.length>0) {
                    [self.rootView pushWebController:posturl];
                }
            }
        }
    }

    return YES;
}


-(void)initIntroView
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (![defaults objectForKey:@"intro_screen_viewed"]) {
        self.introView = [[IntroView alloc] initWithFrame:self.window.frame];
        self.introView.delegate = self;
        [self.window.rootViewController.view addSubview:self.introView];
    }
}
#pragma mark - ABCIntroViewDelegate Methods

-(void)onDoneButtonPressed{
    
    //    Uncomment so that the IntroView does not show after the user clicks "DONE"
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"YES"forKey:@"intro_screen_viewed"];
    [defaults synchronize];

    [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.introView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.introView removeFromSuperview];
    }];
}


- (void)navigationController:(UINavigationController *)navController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
   
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    self.dateRefreshTime = [NSDate date];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
  //  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    self.dateRefreshTime = [NSDate date];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    //hide the badge
    
    NSDate *now = [NSDate date];
    NSTimeInterval duration = [now timeIntervalSinceDate:_dateRefreshTime];
    
    if( duration > 3600 * 0.25 )// || (application.applicationIconBadgeNumber  && strPushToken))
    {//1刻钟
        if([ZApi isConnectionAvailable])
        {
            [self.rootView refreshBaoliao];
            
        }
        
    }
    //   AnalyticsUtil
    if([UIApplication sharedApplication].applicationIconBadgeNumber>0)
    {
         [[NSNotificationCenter defaultCenter] postNotificationName:@"updatebadge" object:nil];
    }
}



- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    [[SDImageCache sharedImageCache] clearMemory];
      DLog(@"%s", __PRETTY_FUNCTION__);
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    //注册远程通知
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)pToken {
    NSString *token=[NSString stringWithFormat:@"%@",pToken];
    token=[token stringByReplacingOccurrencesOfString:@"<" withString:@""];
    token=[token stringByReplacingOccurrencesOfString:@">" withString:@""];
    token=[token stringByReplacingOccurrencesOfString:@" " withString:@""];
    //注册成功，将deviceToken保存到应用服务器数据库中，因为在写向ios推送信息的服务器端程序时要用到这个
    //将上述数据全部存储到NSUserDefaults中
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:token forKey:@"pushToken"];
    //这里建议同步存储到磁盘中，但是不是必须的
    [userDefaults synchronize];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    
    // 处理推送消息
    DLog(@"userInfo == %@",userInfo);
    if (application.applicationState == UIApplicationStateActive)
    {
        id aps = [userInfo objectForKey:@"aps"];
        NSString *msg_type =@"";
        if (aps && [aps isKindOfClass:[NSDictionary class]]) {
            NSArray *keys = [aps allKeys];
            if ([keys containsObject:@"msg_type"]) {
                 msg_type = [aps stringForKey:@"msg_type" withDefaultValue:@""];
            }
        }
        /// 返回Cell高度/* msg_type 0-评论 1-喜欢 2-关注 3-取消关注 4-@你说 5-私信你说 6-删除评论 11-推荐榜单 12-顶了单品
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updatebadge" object:msg_type];
    }else{
        // 这个字典就是推送消息的userInfo
        id aps = [userInfo objectForKey:@"aps"];
        if (aps && [aps isKindOfClass:[NSDictionary class]]){
            NSString *posturl =[aps stringForKey:@"post_url" withDefaultValue:@""];
            if (posturl.length>0) {
                [self.rootView pushWebController:posturl];
            }
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"updatebadge" object:nil];
    }
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
    DLog(@"Regist fail%@",error);
    
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    //如果OpenShare能处理这个回调，就调用block中的方法，如果不能处理，就交给其他（比如支付宝）。
    if ([[BaiChuanShare sharedInstance] handleOpenURL:url]) {
        return YES;
    }

    if ([[ZPlatformShare sharedInstance] handleOpenURL:url]) {
        return YES;
    }
    //如果极简 SDK 不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给 SDK
    if ([url.host isEqualToString:@"safepay"])
    {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"safepay result = %@",resultDic);
            if (_orderDelegate&&[_orderDelegate respondsToSelector:@selector(orderPayOK:)]) {
                [_orderDelegate orderPayOK:resultDic];
            }
        }];
    }else if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
//            NSLog(@"platformapi result = %@",resultDic);
        }];
    }

    return YES;
}

-(void)initStat
{
    [[ZShare sharedInstance] initsearchparams];
    [[ZShare sharedInstance] initdanpinpublicparams:@"index"];
    //
    [BaseModel stat:nil success:^(AFHTTPRequestOperation *operation, id result) {
    } failure:^(NSError *error) {
        
    }];
    [BaseModel updateVer:nil success:^(AFHTTPRequestOperation *operation, id result) {
        DLog(@"%@",result);
        if (result && [result isKindOfClass:[NSDictionary class]]) {
            NSDictionary *res =(NSDictionary*)result;
            int code = [[res objectForKey:@"code"] intValue];
            self.urlstr =[NSString stringWithFormat:@"%@",[res objectForKey:@"url"]];
            if (code==1) {
                UIAlertView *alert=  [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%@",[res objectForKey:@"msg"]] delegate:self cancelButtonTitle:@"稍后更新" otherButtonTitles:@"立即更新", nil];
                alert.tag=1;
                [alert show];
                alert=nil;
            }
        }
    } failure:^(NSError *error) {
        
    }];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            
            break;
        case 1:
        {
            if (alertView.tag==2) {
              
                NSString *str = @"itms-apps://itunes.apple.com/app/id1006667886";
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
                return;
            }else{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.urlstr]];
            }
            
        }
        break;
            
        default:
            break;
    }
}
-(void)commentAlertView
{
    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"去给'%@'打分吧！",appName]
                                                        message:@"您的评价对我们很重要"
                                                       delegate:self
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"稍后评价",@"去评价",nil];
    alertView.tag = 2;
    [alertView show];
    alertView=nil;
}
//=======================================
/* The user activity will be saved (to be continued or persisted). The receiver should update the activity with current activity state.
 */
- (BOOL)application:(nonnull UIApplication *)application continueUserActivity:(nonnull NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray * __nullable))restorationHandler{
    NSString *idetifier = userActivity.title;
    NSLog(@"%s, %@", __FUNCTION__, idetifier);
    NSString *posturl = [[ZSpotLightHelper helper] getItemData:idetifier];
    if (posturl.length>0) {
        [self.rootView pushWebController:posturl];
    }
    return YES;
}

@end
